/********************************************
 * 功能说明: 
 * 模块名称: 
 * 系统名称: 
 * 软件版权: 北京银杉金服科技有限公司
 * 系统版本: 1.0.0
 * 开发人员: zhangfb
 * 开发时间: 2018/9/9 14:49
 * 审核人员: 
 * 相关文档: 
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.hyacinth.service.impl;

import com.hyacinth.constant.IDict;
import com.hyacinth.entity.Resource;
import com.hyacinth.entity.Role;
import com.hyacinth.repository.jpa.ResourceRepository;
import com.hyacinth.repository.jpa.ResourceRoleRepository;
import com.hyacinth.repository.jpa.RoleRepository;
import com.hyacinth.service.RoleService;
import com.hyacinth.util.BeanUtils;
import com.hyacinth.util.JsonMapper;
import com.hyacinth.util.XaUtils;
import com.hyacinth.vo.RoleVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangfb
 * @version 1.0.0.1
 * @since JDK 1.8
 */
@Slf4j
@Service
@Transactional
public class RoleServiceImpl implements RoleService{

    /** 注入持久层 **/
    private final RoleRepository roleRepository;
    private final ResourceRepository resourceRepository;
    private final ResourceRoleRepository resourceRoleRepository;

    @Autowired
    public RoleServiceImpl(RoleRepository roleRepository,
                           ResourceRepository resourceRepository,
                           ResourceRoleRepository resourceRoleRepository) {
        this.roleRepository = roleRepository;
        this.resourceRepository = resourceRepository;
        this.resourceRoleRepository = resourceRoleRepository;
    }

    /**
     * 获取角色资源
     */
    @Override
    public List<RoleVo> findRoleAndResource() {
        // 获取正常状态的角色集合
        List<Role> roleList = roleRepository.findByDataFlag(IDict.dataFlag_OK);
        List<RoleVo> roleVos = new ArrayList<>(roleList.size());
        if (!XaUtils.isEmpty(roleList)) {
            for (Role role : roleList) {
                RoleVo roleVo = new RoleVo();
                try {
                    BeanUtils.copyAllProperties(role, roleVo);
                } catch (Exception e) {
                    log.error("对象转换失败，对象信息：" + JsonMapper.toJsonString(role), e);
                }
                List<Resource> resList = resourceRepository.findResByRoleCode(roleVo.getCode(), IDict.dataFlag_OK);
                roleVo.setResourceList(resList);
                roleVos.add(roleVo);
            }
        }
        return roleVos;
    }
}
